package com.xxx.userdetail;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xxx.domain.Login;
import com.xxx.domain.Permission;
import com.xxx.mapper.PermissionMapper;
import com.xxx.service.ILoginService;
import com.xxx.service.IPermissionService;
import com.xxx.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class LoginUserDetailService implements UserDetailsService {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private IPermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //s 为用户名,根据用户名查询用户信息
        EntityWrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper);
        AssertUtil.isNotNull(login, "用户名或密码不正确,请重新输入");

        //根据登录ID去查询用户对应的权限信息
        List<Permission> permissions = permissionService.selectPermissionByLoginId(login.getId());
        log.info("权限信息:{}", permissions);

        //创建权限集合
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //循环遍历权限信息
        for (Permission permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission.getSn()));
        }
        Login login1 = new Login();
        login1.setId(login.getId());
        login1.setUsername(login.getUsername());

        log.info("用户信息:{}", login1);

        //创建User对象
        User user = new User(
                JSONObject.toJSONString(login1),
                login.getPassword(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                login.getEnabled(),
                authorities);
        return user;
    }
}
